<template>
  <q-page class="prod-page column no-wrap" style="background-color: #F4F6F9">
    <!-- <header class="header">
      <div class="bg"></div>
      <div class="content flex items-center q-px-md q-py-sm">
        <div class="logo center overflow-hidden q-mr-xs" style="border-radius: 4px">
          <img src="~/assets/images/public/logo.png" style="height: 18px" />
        </div>
        <div class="logo center overflow-hidden">
          <img src="~/assets/images/public/logo_text.png" style="height: 12px" />
        </div>
        <div
          class="line q-mx-xs"
          style="background-color: #9f896d; opacity: 0.24; width: 1px; height: 20px"
        ></div>
        <div style="color: #4c3c30; font-size: 13px">如有疑惑请拔打客服电话：4009099558</div>
      </div>
    </header> -->
    <div style="height: 50px;"></div>

    <div style="width: 50%; margin: 0 auto;">
      <q-img src="~/assets/images/prod/image1.png" :ratio="424 / 246" no-spinner />
    </div>
    <section class="q-px-md flex-1 column no-wrap">
      <div class="q-mt-md text-center" style="font-size: 18px; font-weight: bold">恭喜您，初审成功！</div>

      <div class="flex items-center justify-center q-mt-sm">
        <q-icon name="south" size="xs" style="color: #096AFF" />
        <div style="color: #816446">
          <span style="color: #096AFF">安易融</span>根据您的资质，智能匹配以下产品
        </div>
        <q-icon name="south" size="xs" style="color: #096AFF" />
      </div>

      <!-- <div style="height: 10px;"></div> -->

      <section class="flex-1 q-mt-md" style="">
        <!-- 授权列表 -->
        <div
          v-for="(item, index) in approveList"
          :key="index"
          @click="approveClickHandler(item)"
          class="mechanism-item relative-position flex items-center justify-between no-wrap q-mt-md"
        >
          <div class="q-mr-sm q-pb-md relative-position" style="z-index: 3">
            <div class="flex items-center no-wrap">
              <div
                class="flex items-center justify-center mark no-wrap"
                :class="(item.companyName?.length ?? 0) > 7 ? 'mark-lg' : 'mark'"
              >
                <div class="center q-mr-xs overflow-hidden" style="border-radius: 6px">
                  <img :src="item.companyLogo" style="height: 20px" />
                </div>
                <div class="text-white" style="font-size: 15px; white-space: nowrap">
                  {{ item.companyName ?? '' }}
                </div>
              </div>
              <div class="tag ellipsis-2-lines">{{ item.companySubTitle ?? '' }}</div>
            </div>
            <div class="flex items-center q-ml-md">
              <div>
                <div style="color: #8f8f8f; font-size: 12px">最高可借额度(元)</div>
                <div style="font-size: 22px; font-weight: bold; color: #222">
                  {{ (+(+(item.maxLoanAmount ?? 0)).toFixed(0)).toLocaleString() }}
                </div>
              </div>

              <div class="line q-mx-md" style="background-color: #f3f3f3; width: 1px; height: 40px"></div>

              <div>
                <div style="color: #8f8f8f; font-size: 12px">最低年化利率</div>
                <div style="font-size: 14px; color: #222; font-weight: bold">
                  {{ item.minRate ?? 0 }}~{{ item.maxRate ?? 0 }}%
                </div>
              </div>
            </div>
          </div>
          <div
            class="q-pr-md absolute full-width full-height flex items-center justify-end q-pt-sm"
            style="z-index: 1"
          >
            <q-btn
              @click.stop="approveClickHandler(item)"
              unelevated
              rounded
              padding="xs md"
              style="background-color: #096AFF; color: #fff; white-space: nowrap; font-weight: bold"
              label="去申请"
            />
          </div>
        </div>

        <!-- 授权列表结束 -->

        <div
          v-for="(item, index) in showList"
          :key="index"
          @click="gotoProd(item, '' , ProdJumpDialogRef)"
          class="prod-item relative-position flex items-center justify-between no-wrap q-mt-md"
        >
          <div class="q-mr-sm q-pb-md relative-position" style="z-index: 3">
            <div class="flex items-center no-wrap">
              <div class="flex items-center justify-center mark no-wrap">
                <div class="center q-mr-xs overflow-hidden" style="border-radius: 6px">
                  <img :src="item.productLogo" style="height: 20px" />
                </div>
                <div class="text-white" style="font-size: 15px; white-space: nowrap">
                  {{ item.productName ?? '' }}
                </div>
              </div>
              <div class="tag ellipsis-2-lines">{{ item.productLabel ?? '' }}</div>
            </div>
            <div class="flex items-center q-ml-md">
              <div>
                <div style="color: #8f8f8f; font-size: 12px">最高可借额度(元)</div>
                <div style="font-size: 22px; font-weight: bold; color: #222">
                  {{ (+(+item.maxAmount).toFixed(0)).toLocaleString() }}
                </div>
              </div>

              <div class="line q-mx-md" style="background-color: #f3f3f3; width: 1px; height: 40px"></div>

              <div>
                <div style="color: #8f8f8f; font-size: 12px">最低年化利率</div>
                <div style="font-size: 14px; color: #222; font-weight: bold">{{ item.rateAmountInfo }}</div>
              </div>
            </div>
          </div>
          <div
            class="q-pr-md absolute full-width full-height flex items-center justify-end q-pt-sm"
            style="z-index: 1"
          >
            <q-btn
              @click.stop="gotoProd(item, '' , ProdJumpDialogRef)"
              unelevated
              rounded
              padding="xs md"
              style="background-color: #096AFF; color: #fff; white-space: nowrap; font-weight: bold"
              label="去申请"
            />
          </div>
        </div>
      </section>

      <div
        @click="router.push({ path: '/feedback', query: route.query })"
        style="font-size: 13px; color: #096AFF"
        class="text-center q-mt-lg q-mb-xs"
      >
        投诉与建议
      </div>

      <div style="font-size: 12px; color: #999999" class="text-center q-mb-lg">
        <div>客服电话：4009099558</div>
        <div>客服在线时间:周一至周五 9:30-18:30</div>
      </div>
    </section>
    <ProdDialog ref="ProdDialogRef" />
    <ProdJumpDialog ref="ProdJumpDialogRef" />
    <Protocol ref="ProtocolRef" />
  </q-page>
</template>

<script setup lang="ts">
import { getProdUnionResultApi, prodClickCountApi, prodInfoListApi } from 'src/api/prod';
import { showLoadingToast } from 'vant/lib/toast';
import { nextTick, onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { onUnmounted } from 'vue';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ProdItem, ResType, gotoProd } from './prodList';
import ProdDialog from './dialog/ProdDialog.vue';
import { ProdDialogInstance } from './dialog/ProdDialog';
import { useMechanismStore } from 'src/stores/mechanism-store';
import { approveClickCountApi, waitApproveListApi } from 'src/api/merchant';
import { MatchResult, MatchResultOrderItemList } from 'src/types/matchResult';
import Protocol from './dialog/Protocol.vue';
import { ProtocolInstance } from './dialog/Protocol';
import { testMatchResult } from '../mechanism/mock';
import ProdJumpDialog from 'src/components/ProdJumpDialog.vue';
import { ProdJumpDialogInstance } from 'src/components/ProdJump';
const router = useRouter();
const route = useRoute();

const ProdDialogRef = ref<ProdDialogInstance>();
const ProtocolRef = ref<ProtocolInstance>();
const showList = ref<ProdItem[]>([]);
const ProdJumpDialogRef = ref<ProdJumpDialogInstance>();
const prodOneList = ref<ProdItem[]>([]);
const prodTwoList = ref<ProdItem[]>([]);
const approveList = ref<MatchResultOrderItemList[]>([]);

const randomProd = computed(() => {
  if (!prodOneList.value?.length) return null;
  // const list = (() => {
  //   if (prodOneList.value.length && prodTwoList.value.length) {
  //     return [prodOneList.value, prodTwoList.value][Math.floor(Math.random() * 2)]
  //   }
  //   return showList.value
  // })()
  const index = Math.floor(Math.random() * prodOneList.value.length);
  return prodOneList.value[index];
});

const dialogShowHandler = () => {
  if (ProdDialogRef.value?.getShow()) return;
  if (approveList.value.length) {
    const index = Math.floor(Math.random() * approveList.value.length);
    ProdDialogRef.value?.showApprove(approveList.value[index])
    return;
  }
  if (randomProd.value) {
    ProdDialogRef.value?.show(randomProd.value);
  }

};

const initApproveList = async () => {
  const { orderId } = useMechanismStore();
  if (!orderId) return;
  const res = await waitApproveListApi<MatchResult>({ orderNo: orderId });
  approveList.value = res.data.orderItemList;

  // approveList.value = testMatchResult.orderItemList;

  dialogShowHandler();

};

const approveClickHandler = async (item: MatchResultOrderItemList) => {
  if (item.protocolUrl) {
    ProtocolRef.value?.show(item);
    return;
  }
  const { orderId } = useMechanismStore();
  // await approveClickCountApi({ orderNo: orderId, orderItemId: item.orderItemId });
  if (!item.approveUrl) return;
  window.location.href = item.approveUrl;
};

const initData = async () => {
  const toast = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  try {
    const [resOne, resTwo] = await Promise.all([
      prodInfoListApi<ResType>({ sceneId: 1 }),
      prodInfoListApi<ResType>({ sceneId: 2 }),
    ]);
    toast.close();
    prodOneList.value = resOne.data.dataList;
    prodTwoList.value = resTwo.data.dataList;
    showList.value = resOne.data.dataList?.length ? resOne.data.dataList : resTwo.data.dataList;
    dialogShowHandler();
  } catch (error) {
    toast.close();
  }
};
onMounted(() => {
  if (route.query?.jumpUrl) {
    nextTick(() => {
      window.location.href = route.query.jumpUrl as string
    })
  } else {
    initData();
    initApproveList();
  }
});
</script>

<style lang="scss" scoped>

.prod-page {
  background-image: url(src/assets/images/prod/bg.png);
  background-size: 100% auto;
  background-repeat: no-repeat;
}
.header {
  position: relative;
  z-index: 1;
  max-width: 100vw;
  .bg {
    position: absolute;
    z-index: 0;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: linear-gradient(136deg, #ff8854 0%, #ffb270 100%);
    opacity: 0.3;
  }
  .content {
    position: relative;
    z-index: 2;
  }
}

.prod-item {
  background-image: url(src/assets/images/prod/item-bg.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 8px;
  overflow: hidden;
  .mark {
    background-image: url(src/assets/images/prod/mark.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    padding: 6px 24px 14px 12px;
  }
  .tag {
    padding: 1px 6px;
    border-radius: 6px;
    margin-left: -2px;
    margin-bottom: 4px;
    color: #fe6c09;
    font-size: 12px;
    // white-space: nowrap;
    border: 1px solid rgba($color: #fe6c0b, $alpha: 0.4);
  }
}

.mechanism-item {
  background-image: url(src/assets/images/prod/item-bg.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 8px;
  overflow: hidden;
  .mark {
    background-image: url(src/assets/images/prod/mark.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    padding: 6px 24px 14px 12px;
  }
  .mark-lg {
    background-size: 105% 100%;
  }
  .tag {
    padding: 1px 6px;
    border-radius: 6px;
    margin-left: -2px;
    margin-bottom: 4px;
    color: #fe6c09;
    font-size: 12px;
    // white-space: nowrap;
    border: 1px solid rgba($color: #fe6c0b, $alpha: 0.4);
  }
}
</style>
